<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名" prop="fileName">
        <el-input
          v-model="queryParams.fileName"
          placeholder="请输入文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="原始名称" prop="originalName">
        <el-input
          v-model="queryParams.originalName"
          placeholder="请输入原始文件名"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="文件类型" prop="fileType">
        <el-select v-model="queryParams.fileType" placeholder="请选择文件类型" clearable>
          <el-option
            v-for="dict in dict.type.tzai_file_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="业务类型" prop="bizType">
        <el-select v-model="queryParams.bizType" placeholder="请选择业务类型" clearable>
          <el-option
            v-for="dict in dict.type.tzai_file_biz_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
          <el-option label="正常" value="1" />
          <el-option label="停用" value="0" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-upload"
          size="mini"
          @click="handleUpload"
          v-hasPermi="['tzai:file:upload']"
        >上传</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['tzai:file:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['tzai:file:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="fileList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="文件ID" align="center" prop="fileId" width="80" />
      <el-table-column label="预览" align="center" width="100">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.fileType === 'image'"
            :src="getViewUrl(scope.row.fileId)"
            :preview-src-list="[getViewUrl(scope.row.fileId)]"
            fit="cover"
            style="width: 60px; height: 60px; border-radius: 4px;"
          />
          <el-tag v-else :type="getFileTypeTag(scope.row.fileType)">
            {{ getFileTypeLabel(scope.row.fileType) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="原始文件名" align="center" prop="originalName" show-overflow-tooltip />
      <el-table-column label="文件类型" align="center" prop="fileType" width="100">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tzai_file_type" :value="scope.row.fileType"/>
        </template>
      </el-table-column>
      <el-table-column label="文件大小" align="center" prop="fileSize" width="100">
        <template slot-scope="scope">
          {{ formatFileSize(scope.row.fileSize) }}
        </template>
      </el-table-column>
      <el-table-column label="业务类型" align="center" prop="bizType" width="120">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.tzai_file_biz_type" :value="scope.row.bizType"/>
        </template>
      </el-table-column>
      <el-table-column label="业务ID" align="center" prop="bizId" width="80" />
      <el-table-column label="存储平台" align="center" prop="storagePlatform" width="120" />
      <el-table-column label="状态" align="center" prop="status" width="80">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === '1' ? 'success' : 'danger'">
            {{ scope.row.status === '1' ? '正常' : '停用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="上传时间" align="center" prop="createTime" width="160" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-view"
            @click="handleView(scope.row)"
          >查看</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            v-hasPermi="['tzai:file:download']"
          >下载</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['tzai:file:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 上传文件对话框 -->
    <el-dialog title="上传文件" :visible.sync="uploadOpen" width="500px" append-to-body>
      <el-form ref="uploadForm" :model="uploadForm" :rules="uploadRules" label-width="100px">
        <el-form-item label="文件" prop="file">
          <el-upload
            ref="upload"
            :limit="1"
            accept="*"
            :auto-upload="false"
            :on-change="handleFileChange"
            :file-list="fileList"
            drag
          >
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
            <div class="el-upload__tip" slot="tip">支持所有文件类型</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="业务类型" prop="bizType">
          <el-select v-model="uploadForm.bizType" placeholder="请选择业务类型">
            <el-option
              v-for="dict in dict.type.tzai_file_biz_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="业务ID" prop="bizId">
          <el-input v-model="uploadForm.bizId" placeholder="请输入业务关联ID（可选）" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="uploadForm.remark" type="textarea" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitUpload" :loading="uploadLoading">确 定</el-button>
        <el-button @click="cancelUpload">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listFile, getFile, delFile, uploadFile, getFileViewUrl, getFileDownloadUrl } from "@/api/tzai/file";

export default {
  name: "File",
  dicts: ['tzai_file_type', 'tzai_file_biz_type'],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 文件信息表格数据
      fileList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 上传对话框
      uploadOpen: false,
      uploadLoading: false,
      // 上传表单
      uploadForm: {
        file: null,
        bizType: null,
        bizId: null,
        remark: null
      },
      // 上传文件列表
      fileList: [],
      // 上传表单校验
      uploadRules: {
        file: [
          { required: true, message: "请选择文件", trigger: "change" }
        ],
        bizType: [
          { required: true, message: "请选择业务类型", trigger: "change" }
        ]
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        originalName: null,
        fileType: null,
        bizType: null,
        bizId: null,
        status: null
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询文件信息列表 */
    getList() {
      this.loading = true;
      listFile(this.queryParams).then(response => {
        this.fileList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fileId)
      this.multiple = !selection.length
    },
    /** 上传按钮操作 */
    handleUpload() {
      this.uploadOpen = true;
      this.uploadForm = {
        file: null,
        bizType: null,
        bizId: null,
        remark: null
      };
      this.fileList = [];
    },
    /** 文件选择 */
    handleFileChange(file, fileList) {
      this.uploadForm.file = file.raw;
    },
    /** 提交上传 */
    submitUpload() {
      this.$refs["uploadForm"].validate(valid => {
        if (valid) {
          this.uploadLoading = true;
          uploadFile(this.uploadForm.file, this.uploadForm.bizType, this.uploadForm.bizId)
            .then(response => {
              this.$modal.msgSuccess("上传成功");
              this.uploadOpen = false;
              this.getList();
            })
            .finally(() => {
              this.uploadLoading = false;
            });
        }
      });
    },
    /** 取消上传 */
    cancelUpload() {
      this.uploadOpen = false;
      this.uploadForm = {
        file: null,
        bizType: null,
        bizId: null,
        remark: null
      };
      this.fileList = [];
    },
    /** 查看文件 */
    handleView(row) {
      const url = getFileViewUrl(row.fileId);
      window.open(url, '_blank');
    },
    /** 下载文件 */
    handleDownload(row) {
      const url = getFileDownloadUrl(row.fileId);
      window.open(url, '_blank');
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fileIds = row.fileId || this.ids;
      this.$modal.confirm('是否确认删除文件信息编号为"' + fileIds + '"的数据项？').then(function() {
        return delFile(fileIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('tzai/file/export', {
        ...this.queryParams
      }, `file_${new Date().getTime()}.xlsx`)
    },
    /** 获取查看URL */
    getViewUrl(fileId) {
      return getFileViewUrl(fileId);
    },
    /** 格式化文件大小 */
    formatFileSize(bytes) {
      if (!bytes) return '0 B';
      const k = 1024;
      const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
      const i = Math.floor(Math.log(bytes) / Math.log(k));
      return (bytes / Math.pow(k, i)).toFixed(2) + ' ' + sizes[i];
    },
    /** 获取文件类型标签 */
    getFileTypeTag(fileType) {
      const tagMap = {
        'image': 'primary',
        'audio': 'success',
        'video': 'warning',
        'document': 'info',
        'other': 'default'
      };
      return tagMap[fileType] || 'default';
    },
    /** 获取文件类型标签文本 */
    getFileTypeLabel(fileType) {
      const labelMap = {
        'image': '图片',
        'audio': '音频',
        'video': '视频',
        'document': '文档',
        'other': '其他'
      };
      return labelMap[fileType] || '未知';
    }
  }
};
</script>

